/*!

 @Title: layui.upload 单文件上传 - 全浏览器兼容版
 @Author: 贤心
 @License：LGPL

 */

//是否图片文件
var isPicture = function (val) {
    return RegExp('\\w\\.(jpg|png|gif|bmp|jpeg)$', 'i').test(escape(val));
}

//是否音频文件
var isAudio = function (val) {
    return RegExp('\\w\\.(mp3|wav|mid)$', 'i').test(escape(val));
}

//是否视频文件
var isVideo = function (val) {
    return RegExp('\\w\\.(avi|mp4|wma|rmvb|rm|flash|3gp|flv)$', 'i').test(escape(val));
}

//是否Text文件
var isText = function (val) {
    return RegExp('\\w\\.(txt)$', 'i').test(escape(val));
}

//是否Word文件
var isWord = function (val) {
    return RegExp('\\w\\.(doc|docx)$', 'i').test(escape(val));
}

//是否Excel文件
var isExcel = function (val) {
    return RegExp('\\w\\.(xls|xlsx)$', 'i').test(escape(val));
}

//是否PPT文件
var isPPT = function (val) {
    return RegExp('\\w\\.(ppt|pptx)$', 'i').test(escape(val));
}

//是否压缩文件文件
var isZip = function (val) {
    return RegExp('\\w\\.(rar|zip|7z)$', 'i').test(escape(val));
}

var layui_upload_file_tips_onmouseover = function (obj, content) {
    if (!obj)
        return;
    if (!content)
        return;
    var id = layer.tips(content, obj, { time: 0, maxWidth: 0, tips: [2, '#78BA32'] });
    $(obj).attr("lay-preview-tips-id", id);
};
var layui_upload_file_tips_onmouseout = function (obj) {
    if (!obj)
        return;
    var id = $(obj).attr("lay-preview-tips-id");
    if (!id)
        return;
    layer.close(id);
};

//上传文件下载
var layui_upload_file_download = function (obj) {
    if (!obj)
        return;
    var url = $(obj).attr("lay-download-url");
    if (!url)
        return;
    var name = $(obj).attr("lay-download-name");
    var fileFullCache = url.split('/');
    var $a = $("<a></a>").attr("href", url).attr("download", fileFullCache[fileFullCache.length - 1]);
    $a[0].click();
};

//图片预览
var layui_upload_picture_preview = function (src) {
    var json = {
        "title": "", //相册标题
        "start": 0, //初始显示的图片序号，默认0
        "data": [//相册包含的图片，数组格式
            {
                "src": src, //原图地址
                "thumb": "" //缩略图地址
            }
        ]
    };
    layer.photos({
        photos: json,
        shade: 0.3,
        anim: 5,
        shift: 5
    });
}

var layui_upload_audio_preview = function (src) {
    layer.open({
        id: "audio",
        shade: 0.3,
        type: 1,
        title: false,
        closeBtn: 0,
        shadeClose: true,
        skin: 'yourclass',
        area: ['901px', '38px'],
        content: '<audio src="' + src + '" controls="controls" style="width: 900px;height: 34px;"></audio>'
    });
}

var layui_upload_video_preview = function (src) {
    layer.open({
        id: "video",
        shade: 0.3,
        type: 1,
        title: false,
        closeBtn: 0,
        shadeClose: true,
        skin: 'yourclass',
        area: ['901px', '510px'],
        content: '<video src="' + src + '" controls="controls" style="width: 900px;height: 506px;"></video>'
    });
}

//上传文件预览
var layui_upload_file_preview = function (obj) {
    if (!obj)
        return;
    var url = $(obj).attr("lay-preview-url");
    if (!url)
        return;
    if (isPicture(url)) {
        var preview_picture = parent.layui_upload_picture_preview || layui_upload_picture_preview;
        preview_picture(url);
        return;
    }
    if (isAudio(url)) {
        var preview_audio = parent.layui_upload_audio_preview || layui_upload_audio_preview;
        preview_audio(url);
        return;
    }
    if (isVideo(url)) {
        var preview_video = parent.layui_upload_video_preview || layui_upload_video_preview;
        preview_video(url);
        return;
    }
};

var layui_upload_video_preview = function (src) {
    layer.open({
        id: "video",
        shade: 0.3,
        type: 1,
        title: false,
        closeBtn: 0,
        shadeClose: true,
        skin: 'yourclass',
        area: ['901px', '510px'],
        content: '<video src="' + src + '" controls="controls" style="width: 900px;height: 506px;"></video>'
    });
}


layui.define('layer', function (exports) {
    "use strict";

    var $ = layui.jquery;
    var layer = layui.layer;
    var device = layui.device();

    var elemDragEnter = 'layui-upload-enter';
    var elemIframe = 'layui-upload-iframe';

    var msgConf = {
        icon: 2
      , shift: 6
    }, fileTypeName = {
        0: '文件'
      , 1: '图片'
      , 2: '音频'
      , 3: '视频'
      , 4: "记事本"
      , 5: "Word"
      , 6: "Excel"
      , 7: "PPT"
      , 8: "压缩包"
    }, fileTypeIcon = {
        0: 'layui-upload-icon-empty'
      , 1: 'layui-upload-icon-picture'
      , 2: 'layui-upload-icon-audio'
      , 3: 'layui-upload-icon-video'
      , 4: "layui-upload-icon-text"
      , 5: "layui-upload-icon-word"
      , 6: "layui-upload-icon-excel"
      , 7: "layui-upload-icon-powerpoint"
      , 8: "layui-upload-icon-zip"
    };

    //音频播放图标
    var layui_puload_icon_audio_play = "/Scripts/Layui/src/images/png/audio-play.png";
    //视频播放图标
    var layui_puload_icon_video_play = "/Scripts/Layui/src/images/png/video-play.png";

    //获取安全文件类型名
    var getSafeFileTypeName = function (type) {
        return fileTypeName[type] || '文件';
    }

    //获取安全文件类型图标
    var getSafeFileTypeIcon = function (type) {
        return fileTypeIcon[type] || 'layui-upload-icon-empty';
    }

    //获取文件类型
    var getFileType = function (val) {
        if (isPicture(val))
            return 1;
        if (isAudio(val))
            return 2;
        if (isVideo(val))
            return 3;
        if (isText(val))
            return 4;
        if (isWord(val))
            return 5;
        if (isExcel(val))
            return 6;
        if (isPPT(val))
            return 7;
        if (isZip(val))
            return 8;
        return 0;
    }

    //获取文件参数信息
    var getFileOption = function (exts) {
        exts = exts.split("|");
        var typCount = 0;
        var acceptVal = "";
        for (var i = 0; i < exts.length; i++) {
            if (i === 0)
                acceptVal += "." + exts[i];
            else
                acceptVal += ",." + exts[i];
            typCount += getFileType("C:\\file." + exts[i]);
        }
        var fileType = typCount / exts.length;
        return { accept: acceptVal, fileType: fileType };
    }

    //获取鼠标移入触发方法HTML
    var getOnmouseoverHtml = function (url, name, resolution, timeLength, size, creationTime, creator, lastModificationTime, lastModifier) {
        var fileFullCache = url.split('/');
        var fileCache = fileFullCache[fileFullCache.length - 1].split('.');
        if (!isPicture(url) && !isVideo(url))
            resolution = null;
        if (!isAudio(url) && !isVideo(url))
            timeLength = null;
        var tipsHtml = 'layui_upload_file_tips_onmouseover(this, \'';
        tipsHtml += '<table>';
        tipsHtml += '<tr><td class=\\\'layui-upload-group-div-tips\\\'>文 件 名：</td><td>' + (name ? name : fileCache[0]) + '</td></tr>';
        tipsHtml += '<tr><td class=\\\'layui-upload-group-div-tips\\\'>文件类型：</td><td class=\\\'' + fileTypeIcon[getFileType(url)] + '\\\'></td></tr>';
        tipsHtml += '<tr><td class=\\\'layui-upload-group-div-tips\\\'>扩 展 名：</td><td>' + fileCache[1] + '</td></tr>';
        tipsHtml += resolution ? '<tr><td class=\\\'layui-upload-group-div-tips\\\'>分 辨 率：</td><td>' + resolution + '</td></tr>' : '';
        tipsHtml += timeLength ? '<tr><td class=\\\'layui-upload-group-div-tips\\\'>时 长：</td><td>' + timeLength + '</td></tr>' : '';
        tipsHtml += size ? '<tr><td class=\\\'layui-upload-group-div-tips\\\'>大 小：</td><td>' + size + '</td></tr>' : '';
        tipsHtml += creationTime ? '<tr><td class=\\\'layui-upload-group-div-tips\\\'>创建时间：</td><td>' + creationTime + '</td></tr>' : '';
        tipsHtml += creator ? '<tr><td class=\\\'layui-upload-group-div-tips\\\'>创 建 人：</td><td>' + creator + '</td></tr><tr>' : '';
        tipsHtml += lastModificationTime ? ' <td class=\\\'layui-upload-group-div-tips\\\'>修改时间：</td><td>' + lastModificationTime + '</td></tr>' : '';
        tipsHtml += lastModifier ? '<tr><td class=\\\'layui-upload-group-div-tips\\\'>修 改 人：</td><td>' + lastModifier + '</td></tr>' : '';
        tipsHtml += '</table>';
        tipsHtml += '\');';
        return tipsHtml;
    }

    var Upload = function (options) {
        this.options = options;
    };

    //初始化渲染
    Upload.prototype.init = function () {
        var that = this, options = that.options;
        var body = $('body'), elem = $(options.elem || '.layui-upload-file');
        var iframe = $('<iframe id="' + elemIframe + '" class="' + elemIframe + '" name="' + elemIframe + '"></iframe>');

        //插入iframe    
        $('#' + elemIframe)[0] || body.append(iframe);

        return elem.each(function (index, item) {
            item = $(item);
            var url = item.attr('lay-url') || options.url || ''
                , method = item.attr('lay-method') || options.method || 'post'
                , ext = item.attr('lay-ext') || options.ext
                , preview_url = item.attr('lay-preview-url') || (options.preview ? options.preview.url : null)//预览-地址
                , preview_name = item.attr('lay-preview-name') || (options.preview ? options.preview.name : null)//预览-文件名
                , preview_thumbnail = item.attr('lay-preview-thumbnail') || (options.preview ? options.preview.thumbnail : null);//预览-缩略图

            var form = '<form target="' + elemIframe + '" method="' + method + '" key="set-mine" enctype="multipart/form-data" action="' + url + '"></form>';

            var fileTypeOptions = getFileOption(ext);

            var html = '';
            //包裹ui元素
            if (!options.unwrap) {

                var getGroupClass = function () {
                    if (!preview_url)
                        return "layui-upload-default";
                    if (isPicture(preview_url)) {
                        preview_thumbnail = preview_thumbnail || preview_url;
                        return "layui-upload-history-picture";
                    }
                    if (isAudio(preview_url)) {
                        preview_thumbnail = preview_thumbnail || layui_puload_icon_audio_play;
                        return "layui-upload-history-picture";
                    }
                    if (isVideo(preview_url)) {
                        preview_thumbnail = preview_thumbnail || layui_puload_icon_video_play;
                        return "layui-upload-history-picture";
                    }
                    preview_thumbnail = "";
                    return "layui-upload-history-download";
                }

                //获取提示HTML
                var getTipsHtml = function (url, name, item, options) {
                    if (!url)
                        return '';
                    var preview_resolution = item.attr('lay-preview-resolution') || (options.preview ? options.preview.resolution : null) //预览-分辨率
                      , preview_timeLength = item.attr('lay-preview-timeLength') || (options.preview ? options.preview.timeLength : null) //预览-时长
                      , preview_size = item.attr('lay-preview-size') || (options.preview ? options.preview.size : null) //预览-大小
                      , preview_creationTime = item.attr('lay-preview-creationTime') || (options.preview ? options.preview.creationTime : null) //预览-创建时间
                      , preview_creator = item.attr('lay-preview-creator') || (options.preview ? options.preview.creator : null) //预览-创建人
                      , preview_lastModificationTime = item.attr('lay-preview-lastModificationTime') || (options.preview ? options.preview.lastModificationTime : null) //预览-修改时间
                      , preview_lastModifier = item.attr('lay-preview-lastModifier') || (options.preview ? options.preview.lastModifier : null);//预览-修改人;
                    var tipsHtml = ' onmouseover="' + getOnmouseoverHtml(url, name, preview_resolution, preview_timeLength, preview_size, preview_creationTime, preview_creator, preview_lastModificationTime, preview_lastModifier) + '" ';
                    return tipsHtml;
                }

                var tipsHtml = getTipsHtml(preview_url, preview_name, item, options);

                html += ' <div class="' + getGroupClass() + '">';
                html += '     <div class="layui-upload-group">';
                html += '         <div class="layui-box layui-upload-group-btn">' + form;
                html += '             <span class="layui-upload-icon">';
                html += '                  <i class="' + getSafeFileTypeIcon(fileTypeOptions.fileType) + '"></i>' + (item.attr('lay-title') || options.title || ('上传' + getSafeFileTypeName(fileTypeOptions.fileType)));
                html += '             </span>';
                html += '             <div class="layui-upload-progress">';
                html += '                 <div class="layui-upload-progress-bar" role="progressbar" aria-valuenow="45" aria-valuemin="0" aria-valuemax="100" style="width: 0%;">';
                html += '                 </div>';
                html += '             </div>';
                html += '         </div>';
                html += '         <div name="loading" class="layui-upload-group-loading"></div>';
                html += '         <div name="download" class="layui-upload-group-download layui-upload-icon-download" ' + tipsHtml + '  onmouseout="layui_upload_file_tips_onmouseout(this);" onclick="layui_upload_file_download(this);" lay-download-url="' + preview_url + '" lay-download-name="' + preview_name + '" ></div>';
                html += '         <div name="picture" class="layui-upload-group-picture" ' + (preview_thumbnail ? 'style="background: url(' + preview_thumbnail + ') no-repeat;background-size: 38px 38px;"' : '') + tipsHtml + '  onmouseout="layui_upload_file_tips_onmouseout(this);" onclick="layui_upload_file_preview(this);" lay-preview-url="' + preview_url + '" ></div>';
                html += '     </div>';
                html += ' </div>';
            } else {
                html += form;
            }

            html = $(html);

            //拖拽支持
            if (!options.unwrap) {
                html.on('dragover', function (e) {
                    e.preventDefault();
                    $(this).addClass(elemDragEnter);
                }).on('dragleave', function () {
                    $(this).removeClass(elemDragEnter);
                }).on('drop', function () {
                    $(this).removeClass(elemDragEnter);
                });
            }

            //如果已经实例化，则移除包裹元素
            if (item.parent('form').attr('target') === elemIframe) {
                if (options.unwrap) {
                    item.unwrap();
                } else {
                    item.parent().next().remove();
                    item.unwrap().unwrap();
                }
            };

            //添加文件筛选
            item.attr("accept", fileTypeOptions.accept);

            //包裹元素
            item.wrap(html);

            //触发上传
            item.off('change').on('change', function () {
                that.action(this);
            });
        });
    };

    //提交上传
    Upload.prototype.action = function (input) {
        var that = this
           , val = input.value
           , options = that.options, item = $(input)
           , ext = item.attr('lay-ext') || options.ext || ''
           , url = item.attr('lay-url') || options.url || ''
           , method = item.attr('lay-method') || options.method || 'post';

        if (!val) {
            return;
        };

        if (!url) {
            layer.msg('没有设置URL', msgConf);
            return input.value = '';
        }

        if (ext && !RegExp('\\w\\.(' + ext + ')$', 'i').test(escape(val))) {
            layer.msg('不支持该文件格式', msgConf);
            return input.value = '';
        }

        //---------------------工具方法----------------------------

        //字符串是否含有html标签的检测  
        var checkHtml = function (htmlStr) {
            var reg = /<[^>]+>/g;
            return reg.test(htmlStr);
        }

        var isString = function (value) {
            ///	<summary>
            ///	判断是否字符串类型
            ///	</summary>
            return $.type(value) === "string";
        };

        var toObject = function (data) {
            ///	<summary>
            ///	将字符串转换为对象
            ///	</summary>
            ///	<param name="data" type="String">
            ///	 对象字符串
            ///	</param>
            try {
                if (!isString(data))
                    return data;
                return eval('(' + data + ')');
            } catch (e) {
                alert(e);
                return {};
            }
        };

        //---------------------工具方法----------------------------

        var layBefore = item.attr('lay-before');
        var before = layBefore ? toObject(layBefore) : options.before;
        if (before)
            if (before(input) === false)
                return;

        //上传按钮
        var uploadButton = item.parent("form").parent("div");
        //进度条
        var progressBar = uploadButton.children("div").children("div");
        //组DIV
        var groupDiv = uploadButton.parent("div");
        //上传DIV
        var uploadDiv = uploadButton.parent("div").parent("div");
        //加载DIV
        var loadingDiv = groupDiv.children("div[name=loading]");
        //下载DIV
        var downloadDiv = groupDiv.children("div[name=download]");
        //预览DIV
        var pictureDiv = groupDiv.children("div[name=picture]");

        //上传进度条初始化
        var loadingBarInit = function () {
            progressBar.css("width", "0%");
            loadingDiv.html("");
        }

        //预览DIV隐藏
        var pictureHide = function (fun) {
            pictureDiv.animate({ width: "0px" }, "normal", null, function () {
                if (uploadDiv.attr("class") !== "layui-upload-default")
                    uploadDiv.attr("class", "layui-upload-history-download");
                if (fun)
                    fun();
            });
        }

        //预览DIV显示
        var pictureShow = function () {
            uploadDiv.attr("class", "layui-upload-preview-picture");
            pictureDiv.animate({ width: "38px" }, "normal");
        }

        //下载DIV隐藏
        var downloadHide = function (fun) {
            return function () {
                downloadDiv.animate({ width: "0px" }, "normal", null, function () {
                    uploadDiv.attr("class", "layui-upload-default");
                    if (fun)
                        fun();
                });
            }
        }

        //默认下载DIV隐藏
        var defaultDownloadHide = function (fun) {
            pictureDiv.css("width", "0px");
            downloadDiv.animate({ width: "0px" }, "normal", null, function () {
                uploadDiv.attr("class", "layui-upload-default");
                if (fun)
                    fun();
            });
        }

        //下载DIV显示
        var downloadShow = function (fun) {
            return function () {
                uploadDiv.attr("class", "layui-upload-preview-download");
                downloadDiv.animate({ width: "38px" }, "normal", null, function () {
                    if (fun)
                        fun();
                });
            }
        }

        //加载DIV隐藏
        var loadingHide = function (fun) {
            loadingDiv.animate({ width: "0px" }, "normal", null, function () {
                uploadDiv.attr("class", "layui-upload-default");
                if (fun)
                    fun();
                loadingBarInit();
                item.removeAttr("disabled");
            });
        }

        //加载DIV显示
        var loadingShow = function (fun) {
            return function () {
                uploadDiv.attr("class", "layui-upload-loading");
                loadingDiv.animate({ width: "38px" }, "normal", null, function () {
                    if (fun)
                        fun();
                });
            }
        }

        //默认加载DIV显示
        var defaultLoadingShow = function (fun) {
            pictureDiv.css("width", "0px");
            downloadDiv.css("width", "0px");
            uploadDiv.attr("class", "layui-upload-loading");
            loadingDiv.animate({ width: "38px" }, "normal", null, function () {
                if (fun)
                    fun();
            });
        }

        //上传执行
        var uploadRun = function (fileData) {
            return function () {
                var fd = new FormData();
                try {
                    fd.append(input.name, fileData);
                } catch (e) {
                    loadingHide();
                    layer.msg("文件大小超过允许上传最大值", msgConf);
                }
                var xhr = new XMLHttpRequest();
                xhr.upload.addEventListener("progress", uploadProgress, false);
                xhr.addEventListener("load", uploadComplete, false);
                xhr.addEventListener("error", uploadFailed, false);
                xhr.addEventListener("abort", uploadCanceled, false);
                xhr.open(method, url);
                xhr.send(fd);
            }
        }

        //上传进度事件
        function uploadProgress(evt) {
            if (evt.lengthComputable) {
                var percentComplete = Math.round(evt.loaded * 100 / evt.total);
                progressBar.css("width", percentComplete.toString() + "%");
                loadingDiv.html(percentComplete.toString() + "%");
            }
            else {
                progressBar.css("width", "0%");
                loadingDiv.html("");
            }
        }

        //上传完成（成功）事件
        function uploadComplete(evt) {
            loadingDiv.html("100%");
            progressBar.css("width", "100%");
            if (checkHtml(evt.target.responseText) === true) {
                layer.open({
                    id: "upload_error",
                    shade: 0.3,
                    type: 1,
                    title: false,
                    closeBtn: 0,
                    shadeClose: true,
                    skin: 'yourclass',
                    area: ['901px', '510px'],
                    content: evt.target.responseText
                });
                loadingHide();
                return;
            }
            try {
                var res = JSON.parse(evt.target.responseText);
                $.easyui.showFormMessage(res);
                if (res.Code !== $.easyui.state.ok)
                    return;
            } catch (e) {
                loadingHide();
                return layer.msg('请对上传接口返回JSON字符', msgConf);
            }
            var layAfter = item.attr('lay-after');
            var after = layAfter ? toObject(layAfter) : options.after;
            if (!after) {
                loadingHide();
                layer.msg("未添加上传成功回掉方法", msgConf);
                return;
            }
            var afterResult = after(res.Data);
            if (!afterResult || !afterResult.url) {
                loadingHide();
                layer.msg("上传成功回掉方法返回地址无效", msgConf);
                return;
            }

            downloadDiv.attr("lay-download-url", afterResult.url);
            downloadDiv.attr("lay-download-name", afterResult.name);
            pictureDiv.attr("lay-preview-url", afterResult.url);

            var preview_thumbnail = afterResult.thumbnail ? (isPicture(afterResult.thumbnail) ? afterResult.thumbnail : null) : null;

            if (isPicture(afterResult.url)) {
                pictureDiv.css("background", "url(" + (preview_thumbnail || afterResult.url) + ") no-repeat").css("background-size", "38px 38px");
                loadingHide(downloadShow(pictureShow));
            } else if (isAudio(afterResult.url)) {
                pictureDiv.css("background", "url(" + (preview_thumbnail || layui_puload_icon_audio_play) + ") no-repeat").css("background-size", "38px 38px");
                loadingHide(downloadShow(pictureShow));
            } else if (isVideo(afterResult.url)) {
                pictureDiv.css("background", "url(" + (preview_thumbnail || layui_puload_icon_video_play) + ") no-repeat").css("background-size", "38px 38px");
                loadingHide(downloadShow(pictureShow));
            } else {
                loadingHide(downloadShow());
            }
            var onmouseoverHtml = getOnmouseoverHtml(
                afterResult.url,
                afterResult.name,
                afterResult.resolution,
                afterResult.timeLength,
                afterResult.size,
                afterResult.creationTime,
                afterResult.creator,
                afterResult.lastModificationTime,
                afterResult.lastModifier);
            downloadDiv.attr("onmouseover", onmouseoverHtml);
            pictureDiv.attr("onmouseover", onmouseoverHtml);
        }

        //上传失败事件
        function uploadFailed(evt) {
            loadingHide();
            alert("There was an error attempting to upload the file.");
        }

        //上传中断（取消）事件
        function uploadCanceled(evt) {
            loadingHide();
            alert("The upload has been canceled by the user or the browser dropped the connection.");
        }

        item.attr({ "disabled": "disabled" });
        downloadDiv.attr("onmouseover", "");
        pictureDiv.attr("onmouseover", "");
        downloadDiv.attr("lay-download-url", "");
        pictureDiv.attr("lay-preview-url", "");

        var defaultClass = uploadDiv.attr("class");
        if (defaultClass === "layui-upload-default")
            defaultLoadingShow(uploadRun(input.files[0]));
        else if (defaultClass === "layui-upload-history-download" || defaultClass === "layui-upload-preview-download")
            defaultDownloadHide(loadingShow(uploadRun(input.files[0])));
        else
            pictureHide(downloadHide(loadingShow(uploadRun(input.files[0]))));

        input.value = '';
    };

    //暴露接口
    exports('upload', function (options) {
        var upload = new Upload(options = options || {});
        upload.init();
    });
});
